﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FinanSoft.Utilities;
using FinanSoft.Entities;
using FinanSoft.BusinessLayer;
using System.Collections;

namespace FinanSoft.PresentacionComprasyVentas
{
    public partial class frmServicios : Form
    {
        public frmServicios()
        {
            InitializeComponent();
            fillComboBoxMoney();
            fillComboClient();
            fillComboBoxTax();
            fillAccounts();
            radNC.Select();
        }

        private int[] _auxAccIds;
        private int[] _currencyIds;
        private List<int> _accountIds;
        private int[] _taxIds;

        //*********************************** Fill Combo Box ********************************

        private void fillComboBoxTax()
        {
            List<Tax> impuestos = ConfigurationManager.GetInstance().GetTaxes();
            _taxIds = new int[impuestos.Count];
            int taxIndex = 0;
            if (!StoreRoomManager.GetInstance().IsError)
            {
                foreach (Tax impuesto in impuestos)
                {
                    cmbTax.Items.Add(impuesto.Nombre);
                    _taxIds[taxIndex++] = impuesto.IdImpuesto;
                }
            }
            else
            {
                MessageBox.Show(StoreRoomManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
            if (taxIndex > 0) cmbTax.SelectedIndex = 0;
        }

        // Método para llenar el combobox de monedas
        public void fillComboBoxMoney() 
        {
            List<Currency> addedCurrencies = MoneyManager.GetInstance().GetAddedCurrencies();
            _currencyIds = new int[addedCurrencies.Count + 2];
            for (int currencyIndex = 0; currencyIndex < addedCurrencies.Count; currencyIndex++)
            {
                _currencyIds[currencyIndex] = addedCurrencies[currencyIndex].Id;
                cmbCurrency.Items.Add(addedCurrencies[currencyIndex].Name);
            }
            Currency sys = MoneyManager.GetInstance().SystemCurrency;
            _currencyIds[_currencyIds.Length - 2] = sys.Id;
            cmbCurrency.Items.Add(sys.Name);
            Currency local = MoneyManager.GetInstance().LocalCurrency;
            _currencyIds[_currencyIds.Length - 1] = local.Id;
            cmbCurrency.Items.Add(local.Name);
            cmbCurrency.SelectedIndex = cmbCurrency.Items.Count - 1;
        }

        //Método para llenar el combobox de Proveedores y Clientes
        public void fillComboClient()
        {
            Hashtable auxAccountingTable = AuxiliaryAccountManager.GetInstance().GetAuxiliarAccountsList();
            _auxAccIds = new int[auxAccountingTable.Count];
            int auxIndex = 0;
            foreach (AuxiliarAccount auxAccount in auxAccountingTable.Values)
                if (auxAccount.AccountType == Constants.AuxiliarAccountType.client)
                {
                    cmbClient.Items.Add(auxAccount.Name);
                    _auxAccIds[auxIndex++] = auxAccount.AccountID;
                }
            if (cmbClient.Items.Count != Constants.INVALID_ID)
                cmbClient.SelectedIndex = 0;
        }

        private void fillAccounts()
        {
            _accountIds = new List<int>();
            cmbAccounts.Items.Clear();
            AccountingCatalog catalog = CatalogManager.GetInstance().GetAccountingCatalog();
            foreach (Account account in catalog.PrincipalAccounts)
                addAccount(account);
            if(cmbAccounts.Items.Count > 0)
                cmbAccounts.SelectedIndex = 0;
        }

        private void addAccount(Account account)
        {
            if (!account.IsTitle)
            {
                _accountIds.Add(account.AccountID);
                cmbAccounts.Items.Add(account.DisplayName);
            }
            else
                foreach (Account child in account.Children.Values)
                    addAccount(child);
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            Close();
        }

        private bool validateInformation()
        {
            if (cmbAccounts.SelectedIndex == Constants.INVALID_ID || cmbCurrency.SelectedIndex == Constants.INVALID_ID ||
                cmbTax.SelectedIndex == Constants.INVALID_ID || cmbClient.SelectedIndex == Constants.INVALID_ID || 
                txtPrice.Text.Trim().Length == 0 || txtDescription.Text.Trim().Length == 0)
            {
                MessageBox.Show(MessageConstants.MISSING_FIELDS, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void updateTotal()
        {
            if (cmbCurrency.SelectedIndex != Constants.INVALID_ID && txtPrice.Text.Trim().Length > 0)
            {
                double subTotal = Double.Parse(txtPrice.Text);
                Tax tax = ConfigurationManager.GetInstance().GetTax(_taxIds[cmbTax.SelectedIndex]);
                double total = Math.Round(subTotal + subTotal*tax.Porcentaje, 2);
                Currency currency = MoneyManager.GetInstance().GetCurrency(_currencyIds[cmbCurrency.SelectedIndex]);
                lblTotal.Text = "TOTAL: " + currency.Symbol + total.ToString("0.00");
            }
            else
            {
                lblTotal.Text = "TOTAL:";
            }
        }

        private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
            updateTotal();
        }

        private void cmbCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateTotal();
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (validateInformation())
            {
                double amount = Double.Parse(txtPrice.Text);
                Tax tax = ConfigurationManager.GetInstance().GetTax(_taxIds[cmbTax.SelectedIndex]);
                string docType = radNC.Checked ? Constants.NC_ACCOUNTING_ENTRY : Constants.FC_ACCOUNTING_ENTRY;
                bool result = BuySaleManager.GetInstance().SaveDocument(docType, _auxAccIds[cmbClient.SelectedIndex], dateConta.Value,
                    dateEntrega.Value, _currencyIds[cmbCurrency.SelectedIndex], amount, amount * tax.Porcentaje, amount + amount * tax.Porcentaje,
                    _accountIds[cmbAccounts.SelectedIndex], tax, txtDescription.Text);
                if (result)
                {
                    MessageBox.Show(MessageConstants.DOCUMENT_INSERTION_SUCESS, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    cmbAccounts.SelectedIndex = 0;
                    cmbClient.SelectedIndex = 0;
                    cmbCurrency.SelectedIndex = 0;
                    cmbTax.SelectedIndex = 0;
                    txtPrice.Text = "";
                    txtDescription.Text = "";
                }
                else
                    MessageBox.Show(BuySaleManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
